# -----------------------------------------------------------------------
# OpenXenManager
#
# Copyright (C) 2009 Alberto Gonzalez Rodriguez alberto@pesadilla.org
# Copyright (C) 2014 Daniel Lintott <daniel@serverb.co.uk>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#
# -----------------------------------------------------------------------
import re


class oxcWindowVMNetwork:
    """
    Class to manage network of a VM
    """
    def on_acceptdialognetworkrestart_clicked(self, widget, data=None):
        """
        Function called when you accept "changes will take effect when you next restart the VM.." dialog
        """
        self.builder.get_object("dialognetworkrestart").hide()

    def on_acceptremovenetwork_clicked(self, widget, data=None):
        """
        Function called when you accept "remove network interface" confirmation dialog
        """
        treenetwork = self.builder.get_object("treevmnetwork")
        listnetwork = self.builder.get_object("listvmnetwork")
        selection = treenetwork.get_selection()
        if selection.get_selected()[1] != None:
            iter = selection.get_selected()[1]
            self.xc_servers[self.selected_host].vm_remove_interface(self.selected_ref, listnetwork.get_value(iter,6))

        self.builder.get_object("dialogremovenetwork").hide()
    def on_btaddinterface_clicked(self, widget, data=None):
        """
        Function called when you click in "Add interface" button
        """
        self.builder.get_object("dialogaddnetwork").show()
        treeaddnetwork = self.builder.get_object("treeaddnetwork")
        listaddnetwork = self.builder.get_object("listaddnetwork")
        self.xc_servers[self.selected_host].fill_addinterface_network(listaddnetwork)

    def on_cancelremovenetwork_clicked(self, widget, data=None):
        """
        Function called when you cancel "remove network interface" confirmation dialog
        """
        self.builder.get_object("dialogremovenetwork").hide()
    def on_btremoveinterface_clicked(self, widget, data=None):
        """
        Function called when you click in "Remove interface" button on selected network
        """
        # Show the configuration dialog
        self.builder.get_object("dialogremovenetwork").show()
    def on_btpropertiesinterface_clicked(self, widget, data=None):
        """
        Function called when you click in "Properties" button on selected network
        """

        treeeditnetwork = self.builder.get_object("treeeditnetwork")
        listeditnetwork = self.builder.get_object("listeditnetwork")
        treevmnetwork = self.builder.get_object("treevmnetwork")
        listvmnetwork = self.builder.get_object("listvmnetwork")
        selection = treevmnetwork.get_selection()
        # Network properties is a different dialog, is not a "properties" general dialog
        # If some network is selected
        if selection.get_selected()[1] != None:
            iter = selection.get_selected()[1]
            # Show the dialog
            self.builder.get_object("dialogeditnetwork").show()
            ref = listvmnetwork.get_value(iter, 6)
            network_ref = self.xc_servers[self.selected_host].all['VIF'][ref]['network']
            # function "fill_editinterface_network" returns the position of selected network
            current = self.xc_servers[self.selected_host].fill_editinterface_network(listeditnetwork, network_ref)
            # Set the position in the combo
            treeeditnetwork.set_active(current)
            vif = self.xc_servers[self.selected_host].all['VIF'][ref]
            # Fill network information
            if "kbps" in vif['qos_algorithm_params']:
                self.builder.get_object("entryeditlimit").set_text(vif['qos_algorithm_params']["kbps"])
            else:
                self.builder.get_object("entryeditlimit").set_text("")
            # If MAC is auto-generated
            if "MAC_autogenerated" in vif  and vif['MAC_autogenerated']:
                # Enable radio "auto" and disable manual
                self.builder.get_object("radioeditauto").set_active(True)
                self.builder.get_object("radioeditmanual").set_active(False)
                self.builder.get_object("entryeditmac").set_text("")
            else:
                # Else disable radio "auto" and enable manual
                self.builder.get_object("radioeditmanual").set_active(True)
                self.builder.get_object("radioeditauto").set_active(False)
                self.builder.get_object("entryeditmac").set_text(vif['MAC'])
    def on_canceleditnetwork_clicked(self, widget, data=None):
        """
        Function called when you cancel the edit network window
        """
        self.builder.get_object("dialogeditnetwork").hide()
        
    def on_accepteditnetwork_clicked(self, widget, data=None):
        """
        Function called when you accept the edit network window
        """
        treeeditnetwork = self.builder.get_object("treeeditnetwork")
        listeditnetwork = self.builder.get_object("listeditnetwork")
        treevmnetwork = self.builder.get_object("treevmnetwork")
        listvmnetwork = self.builder.get_object("listvmnetwork")
        selection = treevmnetwork.get_selection()
        # Double check if network is selected
        if selection.get_selected()[1] != None:
            iter = selection.get_selected()[1]
            self.builder.get_object("dialogeditnetwork").show()
            ref = listvmnetwork.get_value(iter, 6)
            network_ref = self.xc_servers[self.selected_host].all['VIF'][ref]['network']
            vif = self.xc_servers[self.selected_host].all['VIF'][ref]
            mac = self.builder.get_object("entryeditmac").get_text()
            limit = self.builder.get_object("entryeditlimit").get_text()
            # modify is a flag variable
            modify = False
            if "kbps" in vif['qos_algorithm_params']:
                if self.builder.get_object("entryeditlimit").get_text() != vif['qos_algorithm_params']["kbps"]:
                    modify = True
            else:
                    modify = True
            if "MAC_autogenerated" in vif and vif['MAC_autogenerated']:
                if self.builder.get_object("radioeditmanual").get_active():
                    modify = True
                    self.xc_servers[self.selected_host].vm_add_interface(self.selected_ref, network_ref, mac, limit)
            else:
                if self.builder.get_object("radioeditauto").get_active():
                    mac = ""
                    modify = True

                if vif['MAC'] != self.builder.get_object("entryeditmac").get_text():
                    modify = True
            if network_ref != listeditnetwork.get_value(treeeditnetwork.get_active_iter(),0):
               modify = True
            # if some element was modified..
            if modify:
                # then remove interface
                self.xc_servers[self.selected_host].vm_remove_interface(self.selected_ref, ref)
                network_ref = listeditnetwork.get_value(treeeditnetwork.get_active_iter(),0)
                mac = self.builder.get_object("entryeditmac").get_text()
                limit = self.builder.get_object("entryeditlimit").get_text()
                # Add create again
                self.xc_servers[self.selected_host].vm_add_interface(self.selected_ref, network_ref, mac, limit)
                # And show dialog saying changes will be applied in next reboot
                self.builder.get_object("dialognetworkrestart").show()
        self.builder.get_object("dialogeditnetwork").hide()
    def on_acceptaddnetwork_clicked(self, widget, data=None):
        """
        Function called when you accept "add network" window
        """
        # Get if mac is auto-generated or manual
        if self.builder.get_object("radiomanual").get_active():
            mac = self.builder.get_object("entrymac").get_text()
        else:
            mac = ''
        treeaddnetwork = self.builder.get_object("treeaddnetwork")
        listaddnetwork = self.builder.get_object("listaddnetwork")
        iter =  treeaddnetwork.get_active_iter()
        network_ref = listaddnetwork.get_value(iter, 0)
        limit = self.builder.get_object("entrylimit").get_text()
        # Create new network
        self.xc_servers[self.selected_host].vm_add_interface(self.selected_ref, network_ref, mac, limit)
        # Hide then window
        self.builder.get_object("dialogaddnetwork").hide()
    def on_radiomanual_clicked(self, widget, data=None):
        """
        Function called when on "add new network" you select a "manual" mac
        """
        self.builder.get_object("entrymac").set_sensitive(True)
        mac = self.builder.get_object("entrymac").get_text()
        X = "([a-fA-F0-9]{2}[:|\-]){5}[a-fA-F0-9]{2}"
        c = re.compile(X).search(mac)
        # If characteres in MAC are valid..
        if c:
            # You can accept the dialog
            self.builder.get_object("acceptaddnetwork").set_sensitive(True)
        else:
            # Else not
            self.builder.get_object("acceptaddnetwork").set_sensitive(False)
    def on_radioeditmanual_clicked(self, widget, data=None):
        """
        Function called when on "edit network" you select a "manual" mac
        """
        self.builder.get_object("entryeditmac").set_sensitive(True)
        mac = self.builder.get_object("entryeditmac").get_text()
        X = "([a-fA-F0-9]{2}[:|\-]){5}[a-fA-F0-9]{2}"
        c = re.compile(X).search(mac)
        # If characteres in MAC are valid..
        if c:
            # You can accept the dialog
            self.builder.get_object("accepteditnetwork").set_sensitive(True)
        else:
            # Else not
            self.builder.get_object("accepteditnetwork").set_sensitive(False)
    def on_radioeditauto_clicked(self, widget, data=None):
        """
        Function called when you selet radio "auto" (mac autogenerated)
        On edit network window
        """
        # You can accept the dialog then
        self.builder.get_object("accepteditnetwork").set_sensitive(True)
        # But you cannot edit the mac textfield
        self.builder.get_object("entryeditmac").set_sensitive(False)

    def on_entryeditmac_changed(self, widget, data=None):
        """
        Function called when you edit a "mac" text field
        """
        mac = self.builder.get_object("entryeditmac").get_text()
        X = "([a-fA-F0-9]{2}[:|\-]){5}[a-fA-F0-9]{2}"
        c = re.compile(X).search(mac)
        # If characteres in MAC are valid..
        if c:
            # You can accept the dialog
            self.builder.get_object("accepteditnetwork").set_sensitive(True)
        else:
            # Else not
            self.builder.get_object("accepteditnetwork").set_sensitive(False)
    def on_entrymac_changed(self, widget, data=None):
        """
        Function called when you edit a "mac" text field
        """
        mac = self.builder.get_object("entrymac").get_text()
        X = "([a-fA-F0-9]{2}[:|\-]){5}[a-fA-F0-9]{2}"
        c = re.compile(X).search(mac)
        # If characteres in MAC are valid..
        if c:
            # You can accept the dialog
            self.builder.get_object("acceptaddnetwork").set_sensitive(True)
        else:
            # Else not
            self.builder.get_object("acceptaddnetwork").set_sensitive(False)

    def on_radioauto_clicked(self, widget, data=None):
        """
        Function called when you selet radio "auto" (mac autogenerated)
        On add new network window
        """
        self.builder.get_object("acceptaddnetwork").set_sensitive(True)
        self.builder.get_object("entrymac").set_sensitive(False)

